package com.wang.gallerybackend.manager.websocket;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.wang.gallerybackend.manager.auth.SpaceUserAuthContext;
import com.wang.gallerybackend.manager.auth.SpaceUserAuthManager;
import com.wang.gallerybackend.manager.auth.model.SpaceUserPermissionConstant;
import com.wang.gallerybackend.model.entity.Picture;
import com.wang.gallerybackend.model.entity.Space;
import com.wang.gallerybackend.model.entity.User;
import com.wang.gallerybackend.model.enums.SpaceTypeEnum;
import com.wang.gallerybackend.service.PictureService;
import com.wang.gallerybackend.service.SpaceService;
import com.wang.gallerybackend.service.SpaceUserService;
import com.wang.gallerybackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * websocket 拦截器,建立连接前要校验
 */
@Slf4j
@Component
public class WsHandshakeInterceptor implements HandshakeInterceptor {

	@Resource
	private UserService userService;

	@Resource
	private PictureService pictureService;

	@Resource
	private SpaceService spaceService;

	@Resource
	private SpaceUserAuthManager spaceUserAuthManager;

	/**
	 * 建立连接前要校验
	 * @param request
	 * @param response
	 * @param wsHandler
	 * @param attributes
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
								   Map<String, Object> attributes) throws Exception {

		if (request instanceof ServletServerHttpRequest) {
			HttpServletRequest httpServletRequest = ((ServletServerHttpRequest) request).getServletRequest();
			// 从请求中获取参数
			String pictureId = httpServletRequest.getParameter("pictureId");
			if (StrUtil.isBlank(pictureId)) {
				log.error("缺少图片参数，拒绝握手");
				return false;
			}
			//获取当前登录用户
			User loginUser = userService.getLoginUser(httpServletRequest);
			if (ObjUtil.isEmpty(loginUser)) {
				log.error("用户未登录");
				return false;
			}
			//校验当前用户有没有权限编辑图片
			Picture picture = pictureService.getById(pictureId);
			if (ObjUtil.isEmpty(picture)) {
				log.error("图片不存在");
				return false;
			}
			//校验图片空间权限
			Long spaceId = picture.getSpaceId();
			Space space=null;
			if(spaceId!=null){
				space = spaceService.getById(spaceId);
				if(ObjUtil.isEmpty(space)){
					log.error("空间不存在");
					return false;
				}
				//判断是不是团队空间
				if(space.getSpaceType()!= SpaceTypeEnum.TEAM.getValue()){
					log.error("不是团队空间");
					return false;
				}
				List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
				if(!permissionList.contains(SpaceUserPermissionConstant.PICTURE_EDIT)){
					log.error("用户没有编辑权限");
					return false;
				}

				//设置用户登录信息等属性到websocket Set<spaceId,List<Session>>
				attributes.put("user",loginUser);
				attributes.put("userId",loginUser.getId());
				attributes.put("pictureId",Long.valueOf(pictureId));
			}
		}

		return true;
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

	}
}
